package cn.layku.gateway.filter;

import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import static org.springframework.http.MediaType.APPLICATION_JSON;

/**
 * @description 请求日志
 */
public class RequestFilter implements GlobalFilter, Ordered {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Override
    public int getOrder() {
        //必须小于0才能看到响应结果
        return -100;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put("startTime", System.currentTimeMillis());
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (APPLICATION_JSON.isCompatibleWith(getDelegate().getHeaders().getContentType())) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        DataBufferUtils.release(join);
                        String responseData = new String(content, StandardCharsets.UTF_8);
                        responseData = responseData.replaceAll(":null", ":\"\"");

                        Map<String, Object> requestMap = new HashMap<>();
                        ServerHttpRequest request = exchange.getRequest();
                        requestMap.put("url", request.getURI());
                        Long startTime = exchange.getAttribute("startTime");
                        requestMap.put("time", (System.currentTimeMillis() - startTime) + "ms");
                        LOGGER.info("request->{}", requestMap);
                        LOGGER.info("response->{}", responseData);

                        byte[] uppedContent = responseData.getBytes(StandardCharsets.UTF_8);
                        return bufferFactory.wrap(uppedContent);
                    }));
                } else {
                    return chain.filter(exchange);
                }
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }


}
